﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BoYuan.MvcCodeGenerator.Controllers;
using FineUIMvc;

namespace BoYuan.MvcCodeGenerator.Areas.Public.Controllers
{
    public class DbConfigController : BaseController
    {
        // GET: Public/DbConfig
        public ActionResult Index()
        {
            if (Session["db"] != null)
            {
                ViewBag.db= Session["db"].ToString();
                ViewBag.tables = GetDbInfoList();
            }
            else
            {
                ViewBag.db = ConfigurationManager.AppSettings["ConnectionString"];
                ViewBag.tables = null;
            }
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Btn_DBlink_OnClick(FormCollection fc)
        {
            Session["db"] = fc["ttbDB"];

            try
            {
                var data = GetTableInfos();
                if (data == null || data.Count == 0)
                {
                    AlertError("获取不到数据库的table", false);
                    UIHelper.Result();
                }

                Session["db"] = fc["ttbDB"];

                bindTables(fc);
                return UIHelper.Result();
            }
            catch (Exception exception)
            {
                AlertError("连接数据库异常：" + exception.Message, false);
                return UIHelper.Result();
            }
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult ttbSearchTableName_OnTrigger1Click(FormCollection fc)
        {
            bindTables(fc);
            return UIHelper.Result();
        }

        private void bindTables(FormCollection fc)
        {
            if (Session["db"] != null)
            {
                var cb = UIHelper.CheckBoxList("cbl_tables");
                //cb.LoadData(GetDbInfoList(fc["ttbSearchTableName"]).ToArray());
                cb.DataSource(GetDbInfoList(fc["ttbSearchTableName"]),"Value","Text");
            }
        }

        private dynamic GetDbInfoList(string likeName = "")
        {
            var db = MyInstance();

            var tableList = db.DbMaintenance.GetTableInfoList(false)
                .OrderBy(p => p.Name)
                .Select(p=> new  { Text = p.Name, Value = p.Name })
                .ToList();

            if (likeName.Length == 0)
            {
                return tableList;
            }
            else
            {
                return tableList
                    .Where(p => p.Text.IndexOf(likeName, StringComparison.OrdinalIgnoreCase) >= 0)
                    .OrderBy(p => p.Text)
                    .Select(p => new { Text = p.Text, Value = p.Value })
                    .ToList();
            }
        }

    }
}